package com.agileai.portal.controller.wcm;

import java.util.ArrayList;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.TreeManageHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.ColumnTreeManage;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class ColumnTreeManageHandler
        extends TreeManageHandler {

	public ColumnTreeManageHandler() {
        super();
        this.serviceId = buildServiceId(ColumnTreeManage.class);
        this.nodeIdField = "COL_ID";
        this.nodePIdField = "COL_PID";
        this.moveUpErrorMsg = "该节点是第一个节点，不能上移！";
        this.moveDownErrorMsg = "该节点是最后一个节点，不能下移！";
        this.deleteErrorMsg = "该节点还有子节点，不能删除！";
    }

    protected TreeBuilder provideTreeBuilder(DataParam param) {
        ColumnTreeManage service = this.getService();
        List<DataRow> menuRecords = service.findTreeRecords(param);
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords, "COL_ID",
                                                  "COL_NAME", "COL_PID");

        return treeBuilder;
    }

	@PageAction
	public ViewRenderer focusTab(DataParam param){
		String responseText = FAIL;
		String currentTabId = param.get("currentTabId");
		this.getSessionAttributes().put(ColumnTreeManageHandler.class.getName()+"currentTabId",currentTabId);
		responseText = SUCCESS;
		return new AjaxRenderer(responseText);
	}
    
    protected void processPageAttributes(DataParam param) {
        setAttribute("COL_ENABLED",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getAttributeValue("COL_ENABLED")));
        setAttribute("CHILD_COL_ENABLED",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getAttributeValue("CHILD_COL_ENABLED",
                                                                          "Y")));
		String currentTabId = (String)this.getSessionAttributes().get(ColumnTreeManageHandler.class.getName()+"currentTabId");
		if (StringUtil.isNullOrEmpty(currentTabId)){
			currentTabId = "base";
		}
		this.setAttribute("currentTabId",currentTabId);        
    }

    protected String provideDefaultNodeId(DataParam param) {
        return "00000000-0000-0000-00000000000000000";
    }
    @PageAction
    public ViewRenderer retrieveRefColumns(DataParam param){
    	String responseText = "";
    	try {
    		String columnId = param.get("COL_ID"); 
    		FormSelect formSelect = this.buildRefColumnSelect(columnId);
        	responseText = formSelect.getScriptSyntax("refColumnIds");			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer setupRefColumns(DataParam param){
    	String responseText = "";
    	try {
    		String columnId = param.get("COL_ID");
    		String newRelColumns = param.get("newRelColumns");
    		String[] relColumnArray = newRelColumns.split(",");
    		List<String> newRelColumnList = new ArrayList<String>();
    		ListUtil.addArrayToList(newRelColumnList, relColumnArray);
    		this.getService().addRelColumns(columnId, newRelColumnList);
    		FormSelect formSelect = this.buildRefColumnSelect(columnId);
        	responseText = formSelect.getScriptSyntax("refColumnIds");
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer moveUpRefColumn(DataParam param){
    	String responseText = FAIL;
    	try {
    		String columnId = param.get("COL_ID");
    		String refColumnId = param.get("refColumnIds");
    		this.getService().moveUpColumn(columnId, refColumnId);
    		FormSelect formSelect = this.buildRefColumnSelect(columnId);
        	responseText = formSelect.getScriptSyntax("refColumnIds");
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer moveDownRefColumn(DataParam param){
    	String responseText = FAIL;
    	try {
    		String columnId = param.get("COL_ID");
    		String refColumnId = param.get("refColumnIds");
    		this.getService().moveDownColumn(columnId, refColumnId);
    		FormSelect formSelect = this.buildRefColumnSelect(columnId);
        	responseText = formSelect.getScriptSyntax("refColumnIds");
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer delRefColumn(DataParam param){
    	String responseText = FAIL;
    	try {
    		String columnId = param.get("COL_ID");
    		String refColumnId = param.get("refColumnIds");
    		this.getService().delRelColumn(columnId, refColumnId);
    		FormSelect formSelect = this.buildRefColumnSelect(columnId);
        	responseText = formSelect.getScriptSyntax("refColumnIds");
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }
    
    private FormSelect buildRefColumnSelect(String columnId){
    	FormSelect formSelect = new FormSelect();
        List<DataRow> relColumnRecords = this.getService().findRelColumnRecords(columnId);
    	try {
            formSelect.setKeyColumnName("COL_REL_ID");
            formSelect.setValueColumnName("COL_REL_NAME");
            formSelect.putValues(relColumnRecords);
            formSelect.addHasBlankValue(false); 				
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
        return formSelect;
    }
    
	@PageAction
	public ViewRenderer isExistRelation(DataParam param){
		String responseText = "N";
		String columnId = param.get(this.nodeIdField);
		String resourceId = columnId;
		String resourceType = Resource.Type.InfoColumn;
		boolean isExistSecurityRelation = isExistSecurityRelation(resourceId, resourceType);
		if (isExistSecurityRelation){
			return new AjaxRenderer("existSecurityRelation");
		}
		boolean isExistRelInfomation = getService().existRelInfomation(columnId);
		if (isExistRelInfomation){
			return new AjaxRenderer("existInfomationRelation");
		}
		return new AjaxRenderer(responseText);
	}
	
	private boolean isExistSecurityRelation(String resourceId,String resourceType){
		boolean result = false;
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		List<DataRow> roleList = authorizationConfig.retrieveRoleList(resourceType, resourceId);
		if (roleList != null && roleList.size() > 0){
			result = true;
		}
		List<DataRow> userList = authorizationConfig.retrieveUserList(resourceType, resourceId);
		if (userList != null && userList.size() > 0){
			result = true;
		}
		List<DataRow> groupList = authorizationConfig.retrieveGroupList(resourceType, resourceId);
		if (groupList != null && groupList.size() > 0){
			result = true;
		}
		return result;
	}	
	
    protected boolean isRootNode(DataParam param) {
        boolean result = true;
        String nodeId = param.get(this.nodeIdField,
                                  this.provideDefaultNodeId(param));
        DataParam queryParam = new DataParam(this.nodeIdField, nodeId);
        DataRow row = this.getService().queryCurrentRecord(queryParam);

        if (row == null) {
            result = false;
        } else {
            String parentId = row.stringValue("COL_PID");
            result = StringUtil.isNullOrEmpty(parentId);
        }
        return result;
    }

    protected ColumnTreeManage getService() {
        return (ColumnTreeManage) this.lookupService(this.getServiceId());
    }
}
